/*
 * GHumanUser.java
 * Created on 2 oct 2005
 *
 * Glacéo Internet Platform
 * http://sourceforge.net/projects/chm/
 *
 * Copyright (c) 2005-2007, Jan Janke (VirtualHockey Project)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hockeo.vhbase.utils.data;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.hockeo.vhbase.error.GException;

/**
 * Provides services for dealing with passwords.
 *
 * @version $Id: GPasswordService.java 83 2005-10-09 14:49:39Z jankejan $
 * @author jankejan
 */
public class GPasswordService
{
  private static GPasswordService s_instance;

  /** Private constructor (because of Singleton pattern). */
  private GPasswordService()
  {}

  /**
   * Returns an instance of the GPasswordService.
   */
  public static synchronized GPasswordService getInstance()
  {
    if ( s_instance == null )
      s_instance = new GPasswordService();

    return s_instance;
  }

  /**
   * Computes an MD5 hash for the given plain text.
   *
   * @param plainText the text for which an MD5 hash shall be computed
   * @return the computed hashcode
   * @throws GException if the desired hash algorithm is not available
   */
  public byte[] computeMD5( String plainText ) throws GException
  {
    MessageDigest md = null;

    try
    {
      md = MessageDigest.getInstance( "MD5" );
    }
    catch ( NoSuchAlgorithmException ex )
    {
      throw new GException( "The MD5 hash algorithm is not available.", ex );
    }

    try
    {
      md.update( plainText.getBytes( "UTF-8" ) );
    }
    catch ( UnsupportedEncodingException ex )
    {
      throw new GException( "The UTF-8 encoding is not supported.", ex );
    }

    return md.digest();
  }
}
